<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('auto_money_transactions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('book_id')->comment('账本ID');
            $table->unsignedBigInteger('user_id')->comment('用户ID');
            $table->unsignedBigInteger('category_id')->comment('主分类ID');
            $table->unsignedBigInteger('sub_category_id')->comment('子分类ID');
            $table->tinyInteger('type')->comment('交易类型：1收入，2支出');
            $table->decimal('amount', 10, 2)->comment('金额');
            $table->string('title', 100)->comment('定时记账标题');
            $table->string('description', 255)->nullable()->comment('交易描述');

            // 周期设置
            $table->tinyInteger('period_type')->comment('周期类型：1每日，2每周，3每月，4每年');
            $table->tinyInteger('period_value')->nullable()->comment('周期值：周几(1-7)或月份第几天(1-31)');

            // 执行时间设置
            $table->time('execute_time')->default('09:00:00')->comment('执行时间');
            $table->date('start_date')->comment('开始日期');
            $table->date('end_date')->nullable()->comment('结束日期，为空表示永久');

            // 状态和控制
            $table->tinyInteger('status')->default(1)->comment('状态：0禁用，1启用');
            $table->date('last_executed_date')->nullable()->comment('最后执行日期');
            $table->date('next_execute_date')->nullable()->comment('下次执行日期');
            $table->integer('executed_count')->default(0)->comment('已执行次数');
            $table->timestamps();

            $table->foreign('book_id')->references('id')->on('money_books')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('category_id')->references('id')->on('money_categories')->onDelete('cascade');
            $table->foreign('sub_category_id')->references('id')->on('money_sub_categories')->onDelete('cascade');

            $table->index(['status', 'next_execute_date']);
            $table->index(['user_id', 'status']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('auto_transactions');
    }
};
